﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Infinity.Common.Extensions
{
	public static class DictionaryExtension
	{
		public static bool TryGetValue<TKey, TValue>(
			this Dictionary<TKey, TValue> dictionary, TKey key, Action<TValue> action)
		{
			TValue value;
			if (dictionary != null && dictionary.TryGetValue(key, out value))
			{
				if (action != null)
					action(value);
				return true;
			}
			return false;
		}

		public static TValue CreateOrGetValue<TKey, TValue>(
			this Dictionary<TKey, TValue> dictionary, TKey key, TValue newValue)
		{
			var value = newValue;

			if (dictionary.TryGetValue(key, out value))
				return value;

			dictionary.Add(key, value);

			return value;
		}
	}
}